package cn.itsource.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.itsource.constants.Constants;
import cn.itsource.mapper.DriverSettingMapper;
import cn.itsource.pojo.vo.SettingVo;
import cn.itsource.pojo.domain.DriverSetting;
import cn.itsource.service.IDriverSettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 司机配置 服务实现类
 * </p>
 *
 * @author beishan
 * @since 2024-03-25
 */
@Service
public class DriverSettingServiceImpl extends ServiceImpl<DriverSettingMapper, DriverSetting> implements IDriverSettingService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void creatDriver(Long id) {
        DriverSetting driverSetting = new DriverSetting();
        driverSetting.setId(id);
        driverSetting.setAutoAccept(false);
        driverSetting.setOrientation(false);
        driverSetting.setListenService(false);
        driverSetting.setOrderDistance(0);
        driverSetting.setRangeDistance(0);
        driverSetting.setCreateTime(new Date());
        driverSetting.setDeleted(false);
        driverSetting.setVersion(0);

        super.save(driverSetting);

    }

    /**
     * 开始接单
     * 获取司机配置并上传到redis
     */
    @Override
    public void startWorkHandle() {
        long id = StpUtil.getLoginIdAsLong();
        DriverSetting setting = super.getById(id);
        SettingVo settingVo = SettingVo.builder()
                .order_distance(setting.getOrderDistance())
                .range_distance(setting.getRangeDistance())
                .build();
        redisTemplate.opsForValue().set(String.format(Constants.Redis.DRIVER_ONLINE_KEY, id),settingVo );
    }

    /**
     * 停止接单
     * 将redis中的相关的司机配置删除
     */
    @Override
    public void stopWorkHandle() {
        long id = StpUtil.getLoginIdAsLong();
        //删除配置
        redisTemplate.delete(String.format(Constants.Redis.DRIVER_ONLINE_KEY, id));
        //删除经纬度
        redisTemplate.opsForGeo().remove(Constants.Redis.DRIVER_LOCATION_KEY,id);
    }
}
